package com.hornsun.util;

/**
 * Created by 编译中... on 2018/5/15.
 */


import com.alibaba.simpleimage.ImageWrapper;
import com.alibaba.simpleimage.util.ImageReadHelper;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.IOUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

@Component
@EnableConfigurationProperties(UploadImgProperty.class)
public class UploadImgUtil {

    //spring 中无法注入静态变量，只能通过间接注入的方式，使用 @AutoWired直接报错，使用Resource时
    // 直接报找到了2个同样的bean，但是我其实只有1个这样的Bean。
    @Resource(name = "uploadImgProperty")
    private UploadImgProperty tempUploadProperty;

    private static UploadImgProperty uploadProperty;

    // 在servlet中 会在构造函数之后执行, 同样可以实现  InitializingBean 接口
    @PostConstruct
    private void init() {
        uploadProperty = tempUploadProperty;
    }

    /**
     * 图片上传，默认支持所有格式的图片, 文件默认最大为 2MB
     *
     * @param file
     * @return 图片存储路径
     */
    public static String uploadImage(MultipartFile file) {
        return uploadImageByAcceptType(file, uploadProperty.getAcceptType(), uploadProperty.getMaxSize());
    }

    /**
     * 图片上传，默认支持所有格式的图片
     *
     * @param file
     * @param maxSize 文件最大多少，单位 mb
     * @return 图片存储路径
     */
    public static String uploadImage(MultipartFile file, int maxSize) {
        return uploadImageByAcceptType(file, uploadProperty.getAcceptType(), uploadProperty.getMaxSize());
    }


    /**
     * 上传图片（可限定文件类型）
     *
     * @param file
     * @param acceptTypes "image/png  image/jpeg  image/jpg"
     * @param maxSize     文件最大为2MB
     * @return 图片存储路径。
     */
    public static String uploadImageByAcceptType(MultipartFile file, List<String> acceptTypes, int maxSize) {
        String type = file.getContentType();
        if (!acceptTypes.contains(type)) {
            throw new IllegalArgumentException("图片格式不支持！");
        }
        int size = (int) Math.ceil(file.getSize() / 1024 / 1024);
        if (size > maxSize) {
            throw new IllegalArgumentException("图片过大！");
        }
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        Path path = Paths.get(uploadProperty.getPath());
        String filePath = path.toAbsolutePath().toString();
        File fileDir = new File(filePath);
        fileDir.mkdirs();
        String uuid = UUID.randomUUID().toString();
        String fileName = uuid+ suffix;
        File realFile = new File(fileDir, fileName);
        FileOutputStream  out = null;
        try {
            IOUtils.copy(file.getInputStream(), out=new FileOutputStream(realFile));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (out!=null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //图片压缩
        long realSize = file.getSize();
        double scale = 1.0d ;
        if(realSize >= 200*1024){
            if(realSize > 0){
                scale = (200*1024f) / realSize  ;
            }
        }

        //拼接文件路劲
        String thumbnailFilePathName = filePath + "/" +uuid+"small" ;

        FileInputStream inStream = null;
        try {
            File in = new File(filePath+ "/" +fileName);
            inStream= new FileInputStream(in);
            ImageWrapper imageWrapper = ImageReadHelper.read(inStream);
            if(realSize<200*1024){
                Thumbnails.of(imageWrapper.getAsBufferedImage()).scale(1f).outputFormat("jpg").toFile(thumbnailFilePathName);
            }else{
                Thumbnails.of(imageWrapper.getAsBufferedImage()).scale(1f).outputQuality(scale).outputFormat("jpg").toFile(thumbnailFilePathName);
            }
        } catch (Exception e1) {
            throw new RuntimeException("图片压缩失败！");
        }finally {
            try {
                if (inStream!=null) {
                    inStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        deleteFile(filePath+ "/" +fileName);
        return uuid;
    }

    private static boolean deleteFile(String sPath) {
        boolean flag = true;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            flag = file.delete();
        }
        return flag;
    }
}
